import * as signalR from "@microsoft/signalr";
import { getToken } from '@/utils/token-util';
import { API_BASE_URL } from '@/config/setting';
export default {
  signalR: {},
  //初始化连接
  initSignalR: function() {
    let that = this;
    if (!getToken()) return;
    let token = getToken().replace("Bearer ","");
    // 禁用协商
    const options = {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets,
      };
    // 传送token
    options.accessTokenFactory = ()=>encodeURI(token);

    // 2.初始化连接
    that.signalR = new signalR.HubConnectionBuilder()
      .withUrl(API_BASE_URL + "/MessageHub", options)
      .withAutomaticReconnect()
      .build();
    // 3.携带参数
    that.signalR.qs = {
      enc_auth_token: encodeURI(token),
    };

    // 4.启动连接的方法
    async function start() {
      try {
        await that.signalR.start();
        console.log("signaIR连接成功");
        
      } catch (err) {
        console.log("err", err);
        // setTimeout(start, 5000);
      }
    }

    // 5.关闭之后重连
    that.signalR.onclose(async () => {
      await start();
    });
    // 6.启动连接
    start();
  },
  // 停止连接（这个方法好像没啥用，先放着吧）
  stopSR: function() {
    let that = this;
    async function stop() {
      try {
        await that.signalR.stop();
        console.log("signaIR退出成功");
      } catch (err) {}
    }
    stop();
  },
};